<template>
  <div class="handler-edit-form" :style="{ height: mainContextHeight - 32 + 'px' }">
    <OnlineEditForm
      :style="{ width: pageWidth }"
      v-if="isReady && formParams"
      v-bind="formParams"
      mode="pc"
      :dialog="dialog"
    />
  </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router';
import { useLayoutStore } from '@/store';
import OnlineEditForm from '../OnlinePageRender/OnlineEditForm/index.vue';
import { ANY_OBJECT } from '@/types/generic';
import { DialogProp } from '@/components/Dialog/types';

const mainContextHeight = inject('mainContextHeight', 200);

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();

// 从路由中获取完整的缓存id
const cacheId = route.fullPath;

const isReady = ref(false);

const formParams = ref<ANY_OBJECT | null>(null);

const pageWidth = ref('100%');

const pageCallback = ref<() => void | null>(null);

const onClosePage = () => {
  router.go(-1);
  layoutStore.removeCachePage(cacheId);
};

// 模拟dialog的回调
const dialog = ref<DialogProp<ANY_OBJECT>>({
  index: cacheId,
  cancel: () => {
    pageCallback.value?.();
    onClosePage();
  },
  submit: (data: ANY_OBJECT) => {
    pageCallback.value?.(data);
    onClosePage();
  },
});

// 获取缓存的表单参数
const getCachedFormParams = () => {
  const cachedParams = layoutStore.editFormParams.find(item => item.id === cacheId);
  if (cachedParams) {
    formParams.value = JSON.parse(cachedParams.formParams) as ANY_OBJECT;
    pageWidth.value = formParams.value?.formConfig?.pageWith || '100%';
    pageCallback.value = cachedParams.callback;
    isReady.value = true;
  } else {
    onClosePage();
  }
};

onMounted(() => {
  getCachedFormParams();
});
</script>

<style lang="scss" scoped>
.handler-edit-form {
  height: 100%;
  justify-content: center;
  align-items: center;
}
</style>
